<template>
  <div class="app-container">
    <el-row>
      <el-col style="padding: 8px 10px 8px 0px" :span="1.5">
        <el-button
          v-for="(btn, index) in operates.list.filter(
            item => item.status == '1' && item.location === '2'
          )"
          :key="index"
          :type="btn.styleType"
          :icon="btn.icon"
          size="mini"
          v-preventReClick
          @click="clickEvent(btn)"
          :disabled="
            btn.show != null && btn.show != undefined && btn.show != ''
              ? !dynamicEval($data, btn.show)
              : false
          "
          >{{ btn.name }}
        </el-button>
      </el-col>
      <el-popover
        title="列筛选"
        trigger="click"
        style="float: right; margin-right: 10px"
      >
        <el-checkbox
          style="display: block"
          v-for="(item, index) in tableData"
          :key="index"
          :label="item.name"
          v-model="item.show"
          >{{ item.name }}
        </el-checkbox>
        <el-button size="small" slot="reference">
          <i class="el-icon-arrow-down el-icon-menu"></i>
        </el-button>
      </el-popover>
    </el-row>

    <!--数据-->
    <dynamic-table
      ref="dyTable"
      @updateList="getList"
      :list="list"
      @handleSelectionChange="handleSelectionChange"
      @editChanged="editChanged($event)"
      :options="options"
      :columns="tableData"
      :operates="operates"
      :diff="110"
    >
    </dynamic-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--    列表-->
    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-if="open"
      width="50%"
      append-to-body
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <dynamic-form
        :addform="addFormData"
        :form="form"
        :rules="rules"
        :addurl="addurl"
        v-on:openChanged="openChanged($event)"
      >
      </dynamic-form>
    </el-dialog>

    <el-dialog
      ref="formTabel"
      :title="title"
      :visible.sync="topen"
      v-if="topen"
      width="80%"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <dynamic-form-table
        :exsitId="exsitId"
        :geturl="geturl"
        :submiturl="addurl"
        v-on:openChanged="openChanged($event)"
        :table="table"
        :form="form"
        :toolbar="toolbar"
        :command="command"
      >
      </dynamic-form-table>
    </el-dialog>
    <portal-dialog :params="portaldialog" />
    <el-dialog
      :visible.sync="progress.open"
      v-if="progress.open"
      :before-close="
        () => {
          return false
        }
      "
      title="下载进度"
      width="30%"
    >
      <el-progress type="circle" :percentage="progress.percent"></el-progress>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dynamicForm from '@/views/components/dynamicForm'
import dynamicTable from '@/views/components/dynamicTable'
import {
  baseRequest,
  getConfigInfo,
  getDataList,
  getData,
  delData,
  exportData,
  getAddForm
} from '@/api/dynamic/dynamic'
import { addDownload, getDownloadUrl } from '@/api/pms/download'
import dynamicFormTable from '@/views/components/dynamicFormTable'
import { deepClone, filter2sub } from '@/utils'
import { getToken } from '@/utils/auth'
import { handleBatchDownload } from '@/utils/zipdownload'
import { uploadObj } from '@/settings.js'
export default {
  name: 'globalSearch',
  components: {
    dynamicTable,
    dynamicForm,
    dynamicFormTable,
    portalDialog: () => import('@/views/components/portalDialog')
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 单一选中id
      ids: [],
      selected: [],
      // 总条数
      total: 0,
      // 文档表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      topen: false,
      options: {
        // table 的参数
        stripe: true, // 是否为斑马纹 table
        loading: false, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: true // 是否支持列表项选中功能
      },
      path: '',
      params: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        searchValue: ''
      },
      queryConfigParams: {},
      searchFormData: [],
      // 表单参数
      form: {},
      addFormData: [],
      tableData: [],
      // 按钮
      operates: {
        // 列操作按钮
        width: 150,
        list: []
      },
      rules: {},
      route: '',
      addurl: '',
      pId: '',
      exsitId: [],
      geturl: '',
      table: '',
      toolbar: '',
      command: '',
      portaldialog: {
        open: false,
        title: 'title',
        portal: {},
        root: null
      },
      progress: {
        open: false,
        percent: 0
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: uploadObj.upload1
      }
    }
  },
  created() {
    let params = this.$route.query
    if (window.route) {
      params = JSON.parse(JSON.stringify(window.route.query))
      delete window.route
    }
    if (params.pageParams) {
      if (typeof params.pageParams == 'string') {
        this.params = params = JSON.parse(
          sessionStorage.getItem('globalSearch' + this.$route.params.Id)
        )
      } else {
        sessionStorage.setItem(
          'globalSearch' + this.$route.params.Id,
          JSON.stringify(params)
        )
      }
      this.pId = this.pId ? this.pId : this.$route.params.Id
      this.path = params.pageParams.url.split('?')[0]
      var str = params.pageParams.url.split('?')
      if (str.length > 1) {
        var paramsStr = str[1].split('=')
        this.queryParams[paramsStr[0]] = this.pId
      }
      this.queryConfigParams.table = params.pageParams.table
    } else {
      this.path = this.$route.path.split('？')[0]
      var str = this.$route.path.split('？')
      if (str.length > 1) {
        var paramsStr = str[1].split('=')
        this.queryParams[paramsStr[0]] = paramsStr[1]
        this.params = paramsStr
      }
      let pageParams = JSON.parse(
        this.$route.meta.pageParams.replace(/'/g, '"')
      )
      if (pageParams) {
        this.queryConfigParams.table = pageParams.table
      } else {
        this.msgError('缺少参数')
        return false
      }
    }
    this.getConfig()
  },
  updated() {
    let ele = this.$refs.dyTable
    if (ele) {
      ele.tableresize()
    }
  },
  methods: {
    //更多属性
    moreattr() {
      var div = document.getElementById('more-list')
      if (div.style.display === 'none') {
        div.style.display = 'block'
        document
          .getElementById('more-attr')
          .setAttribute('icon', 'el-icon-arrow-up')
      } else {
        div.style.display = 'none'
        document
          .getElementById('more-attr')
          .setAttribute('icon', 'el-icon-arrow-down')
      }
    },
    //查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    //重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 30,
        searchValue: ''
      }
      this.handleQuery()
    },
    /** 获取配置信息 */
    getConfig() {
      this.loading = true
      getConfigInfo(this.queryConfigParams).then(response => {
        this.tableData = response.data.tableData
        // if (response.data.tableData.length > 0)
        //   this.updateTempDicts(response.data.tableData);
        this.searchFormData = response.data.searchFormData
        this.operates.list = response.data.commandData
        this.queryParams.searchValue = this.$globalSearch.val
        if (this.$globalSearch.policyid) {
          this.queryParams.policyid = this.$globalSearch.policyid
        }
        if (this.$globalSearch.typeid) {
          this.queryParams.typeid = this.$globalSearch.typeid
        }
        this.getList()
        this.loading = false
      })
    },
    /** 查询列表数据 */
    getList() {
      this.loading = true
      getDataList('/doc/list', this.queryParams).then(response => {
        // getDataList("/pmsproject/list", this.queryParams).then((response) => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selected = selection
    },
    // 按钮点击事件
    clickEvent(obj) {
      let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'))
      if (obj.type === '2') {
        this.$router.push({ path: obj.url })
        if (pageParams.handle == 'handleDownload') {
          this.handleDownload()
        }
      } else {
        if (pageParams.condition) {
          if (!this.jugeCondition(pageParams.condition).flag) {
            return false
          }
        }
        if (pageParams.handle == 'handleDelete') {
          this.handleDelete(obj.url)
        } else if (pageParams.handle == 'handleExport') {
          this.handleExport(obj.url)
        } else if (pageParams.handle == 'handleAdd') {
          if (pageParams.type == 'table') {
            this.handleAddExited(obj)
          } else {
            if (obj.sub)
              this.handleAdd(obj.url, pageParams.addForm, obj.name, true)
            else this.handleAdd(obj.url, pageParams.addForm, obj.name)
          }
        } else if (pageParams.handle == 'handleAddAssign') {
          this.handleAddAssign(obj)
        } else if (pageParams.handle == 'handlePortal') {
          this.handlePortal(obj.name, pageParams.portal)
        } else if (pageParams.handle == 'handleConfirm') {
          this.handleConfirm(
            obj.url,
            pageParams.method,
            obj.name,
            pageParams.condition
          )
        } else if (pageParams.handle == 'handleUpdate') {
          this.handleUpdate(obj.url, pageParams.addForm, obj.name)
        } else if (pageParams.handle == 'handleImport') {
          this.handleImport(obj.url, obj.name)
        }
      }
    },
    handleConfirm(url, method, title, condition) {
      let jugement = this.jugeCondition(condition, url, title)
      if (jugement.flag) {
        this.$confirm(jugement.info, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            baseRequest(jugement.route, method, {}, {}).then(response => {
              if (response.code == 200) {
                this.msgSuccess(response.msg)
                this.getList()
                return true
              } else {
                this.msgError(response.msg)
                return true
              }
            })
          })
          .catch(() => {
            this.msgInfo('已取消')
          })
      }
    },
    handlePortal(title, portal) {
      this.portaldialog.open = true
      this.portaldialog.title = title
      this.portaldialog.portal = { portal }
      this.portaldialog.root = this
    },
    /** 新增按钮操作 */
    handleAdd(url, str, title) {
      title = title ? title : '新增'
      this.addurl = url
      this.form = {}
      this.getFormData(str, true)
      this.open = true
      this.title = title
    },
    /** 转换选项数据结构 */
    optionNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          value: item.id,
          label: item.description,
          parentid: item.parentid
        }
      })
      return this.handleTree(data, 'value')
    },
    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel
        }
      })
      return data
    },
    /**  添加已存在*/
    handleAddExited(obj) {
      let pageParams = eval('(' + obj.pageParams + ')')
      this.addurl = obj.url
      this.table = pageParams.table
      this.toolbar = pageParams.toolbar
      this.command = pageParams.command
      if (pageParams.getUrl.indexOf('{') != -1) {
        var url = pageParams.getUrl.substring(0, pageParams.getUrl.indexOf('{'))
        this.geturl = url + this.projectid
      } else {
        this.geturl = pageParams.getUrl
      }
      if (obj.sub) {
        this.form = {
          projectid: this.projectid,
          parentid: this.parentid,
          toid: this.form.toid,
          formid: this.ids[0],
          pmsid: this.form.pmsid
        }
        this.subtopen = true
        this.subtitle = obj.name
      } else {
        this.copy_geturl = this.geturl
        if (this.ids.length > 0)
          this.form = {
            projectid: this.dataInfo.projectid
              ? this.dataInfo.projectid
              : this.dataInfo.id,
            parentid: this.parentid,
            toid: this.ids[0]
          }
        else
          this.form = {
            projectid: this.dataInfo.projectid
              ? this.dataInfo.projectid
              : this.dataInfo.id,
            parentid: this.parentid
          }
        if (this.dataInfo.projectid) this.form['pmsid'] = this.projectid
        this.title = obj.name
        this.topen = true
      }
    },
    /** 添加已存在*/
    handleAddAssign(obj) {
      let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'))
      this.addurl = obj.url
      this.title = obj.name
      this.table = pageParams.table
      this.toolbar = pageParams.toolbar
      this.command = pageParams.command
      this.geturl = pageParams.getUrl
      this.form = { pmsid: this.pId, projectid: this.projectid }
      this.topen = true
    },
    /** 修改按钮操作 */
    handleUpdate(url, str, title) {
      if (this.ids.length != 1) {
        this.msgInfo('请选择一条数据')
        return false
      }
      this.addurl = url
      this.getFormData(str, false)
      this.form = {}
      getData(this.addurl, this.ids[0]).then(response => {
        this.form = response.data
        this.open = true
        this.title = val.title ? val.title : '编辑'
      })
    },
    /** 删除按钮操作 */
    handleDelete(url) {
      const ids = this.ids
      this.$confirm(
        '是否确认删除编号为"' +
          (Array.isArray(ids) && ids.length > 2 ? ids[0] + '等' : ids) +
          '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delData(url, ids)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function() {})
    },
    /** 批量文件下载 */
    handleDownload() {
      if (this.selected.length > 0) {
        let fileArray = []
        let doc_ids = []
        let doc_name = []
        this.selected.forEach(item => {
          fileArray = fileArray.concat(item.fileList)
          doc_ids.push(item.id)
          doc_name.push(item.name)
        })
        if (fileArray.length > 0) {
          if (fileArray.length > 1) {
            handleBatchDownload(fileArray, doc_name, doc_ids, this)
          } else {
            if (fileArray[0].path) {
              /**文件下载*/
              // let url = "http://8.135.99.28:81" + fileArray[0].path;
              let url = this.settings.fileUrl + fileArray[0].path
              // 生成一个a标签
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.download = downloadName
              document.body.appendChild(link)
              link.click()
              /**文件下载*/
              /**S3文件下载
              var fileUrl = fileArray[0].path;
              var index = fileUrl.lastIndexOf("/");
              var bucket = fileUrl.substring(0, index);
              var downloadName = fileArray[0].fileName;
              getDownloadUrl(bucket, downloadName, fileArray[0].docId).then(
                (response) => {
                  if (response.url !== "") {
                    let url = response.url;
                    // 生成一个a标签
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.download = downloadName;
                    document.body.appendChild(link);
                    link.click();
                  } else {
                    this.msgError("文件地址出错");
                  }
                }
              );
              /**S3文件下载*/
            } else {
              this.msgError('文件地址出错')
            }
          }
          addDownload({
            docId: doc_ids.toString(),
            docName: doc_name.toString()
          })
        }
      }
    },
    /** 导入按钮操作 */
    handleImport(url, title) {
      this.upload.title = title
      this.upload.url = process.env.VUE_APP_BASE_API + url
      this.upload.open = true
    },
    /** 导出按钮操作 */
    handleExport(url) {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return exportData(url, queryParams)
        })
        .then(response => {
          this.download(response.msg)
        })
        .catch(function() {})
    },
    openChanged(val) {
      this.open = false
      this.topen = false
      this.getList()
    },
    editChanged(val) {
      this.addurl = val.url
      this.getFormData(val.str, false)
      this.form = {}
      getData(val.url, val.id).then(response => {
        this.form = response.data
        this.open = true
        this.title = val.title ? val.title : '编辑'
      })
    },
    //获取表单数据
    getFormData(str, flag) {
      let formData = {}
      let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
      getAddForm({ addForm: str }).then(response => {
        formData = response.data
        formData.forEach((item, index) => {
          if (
            item.componentType === 'el-select' ||
            item.componentType === 'el-selects' ||
            item.componentType === 'el-radio' ||
            item.componentType === 'el-checkbox-group'
          ) {
            if (
              item.prop === 'policyid' ||
              item.prop === 'stateid' ||
              item.prop === 'ownerid'
            ) {
              formData[index].optionValue = optionData[item.optionValue]
            } else {
              if (
                this.tempDicts[item.prop] &&
                this.tempDicts[item.prop].length > 0
              ) {
                formData[index].optionValue = this.selectNormalizer(
                  deepClone(this.tempDicts[item.prop])
                )
              } else {
                if (item.optionValue.indexOf('url') > -1) {
                  let url = this.getUrl(item.optionValue.split(':')[1])
                  getDataList(url).then(response => {
                    if (response.code == 200) {
                      formData[index].optionValue = response.rows
                    }
                  })
                } else {
                  this.getDicts(item.optionValue).then(response => {
                    this.tempDicts[item.prop] = deepClone(response.data)
                    formData[index].optionValue = this.selectNormalizer(
                      response.data
                    )
                  })
                }
              }
            }
          }
          if (item.componentType === 'el-cascader') {
            let optionarr = item.optionValue.split('?')
            if (optionarr.length > 1) {
              this.optionNormalizer(optionData[optionarr[0]])
              let typearr = []
              optionData[optionarr[0]].forEach(titem => {
                if (titem.value === parseInt(optionarr[1])) {
                  typearr.push(titem)
                  formData[index].optionValue = typearr
                }
              })
            } else {
              formData[index].optionValue = this.optionNormalizer(
                optionData[item.optionValue]
              )
            }
          }
        })
        this.addFormData = formData
        if (flag) {
          for (let item of this.addFormData) {
            if (this.form[item.prop] == undefined) {
              this.$set(
                this.form,
                item.prop,
                item.defaultValue ? item.defaultValue : null
              )
            }
          }
        }
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style>
#more-list {
  background-color: rgb(220, 223, 230);
  padding: 10px;
}
</style>
